package com.obas.view
{
	import com.ease.framework.CommandCompletionEvent;
	import com.obas.business.parameterpool.vo.ParameterPoolGrid;
	import com.obas.business.parameterpool.vo.ParameterPoolListObject;
	import com.obas.event.ParameterPoolEvent;
	import com.obas.flex.common.util.ResourceUtil;
	import com.obas.model.business.ParameterPool;
	import com.obas.model.business.ParameterType;
	import com.ease.component.managers.ErrorManager;

	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;

	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;
	import mx.controls.TextInput;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.ClassFactory;
	import mx.core.IFactory;
	import mx.events.DataGridEvent;
	import mx.events.ListEvent;
	import mx.utils.ArrayUtil;

	[Event(name="{com.obas.event.ParameterPoolEvent.REQUEST_ID}", type="com.obas.event.ParameterPoolEvent")]
	public class ParameterPoolViewMediator extends EventDispatcher
	{

		private static var DATA_FIELD_PREFIX:String="PT";

		private static var DATA_FIELD_PARAMETER_ID:String="PARAMETER_ID";
		private static var DATA_FIELD_PARAMETER_TYPE_ID:String="parameterTypeId";

		private static var DATA_FIELD_DUMMY_PARAMETER_ID:String="$PARAMETER_ID";

		private var _view:ParameterPoolView;

		public var itemRendererFactory:IFactory=new ClassFactory(mx.controls.TextInput);

		private var _dummyParameterIdSequence:Number=1;

		private var updateParameterIds:Array = new Array();
		private var removeParameterIds:Array = new Array();
//		public var _testcaseScriptId:Number;


		[InjectableView]
		/**
		 * The mediator's view.
		 */
		public function get view():ParameterPoolView
		{
			return _view;
		}

		public function set view(value:ParameterPoolView):void
		{
			_view=value;
			init();
		}

		public function init():void
		{
			view.loadBtn.addEventListener(MouseEvent.CLICK, onLoad);
			view.createBtn.addEventListener(MouseEvent.CLICK, onCreate);
			
//			view.cloneBtn.addEventListener(MouseEvent.CLICK, onClone);
//            dispatchEvent(new ItestOperationEvent([_view.viewId]));
			view.parameterPoolDataGrid.addEventListener(DataGridEvent.ITEM_EDIT_END, onItemEditEnd);
		}

		private function onItemEditEnd(event:DataGridEvent):void {

			switchEditLabel(true);

			var editor:TextInput = TextInput(event.currentTarget.itemEditorInstance);			
			var value:String = editor.text;

			var data:Object = event.currentTarget.editedItemRenderer.data;
			data[event.dataField]=value;

			var parameterId:Object = data[DATA_FIELD_PARAMETER_ID];
			if(!parameterId) {
				var dummyParameterId:Object = data[DATA_FIELD_DUMMY_PARAMETER_ID];
				if(!dummyParameterId) {
					data[DATA_FIELD_DUMMY_PARAMETER_ID]=_dummyParameterIdSequence++;
				}
			} else {
				updateParameterIds.push(parameterId);
			}
		}

		private function switchEditLabel(value:Boolean):void {
			if(value) {
				view.editLabel.text="*"+view.editLabel.toolTip;
				view.editLabel.setStyle("fontStyle","italic");
				if(false==view.saveBtn.enabled){
					view.saveBtn.enabled=true;
					view.saveBtn.addEventListener(MouseEvent.CLICK, onSave);
				}
			} else {
				view.editLabel.text=view.editLabel.toolTip;
				view.editLabel.setStyle("fontStyle","normal");
				if(true==view.saveBtn.enabled){
					view.saveBtn.enabled=false;
					view.saveBtn.removeEventListener(MouseEvent.CLICK, onSave);
				}
			}
		}

		private function onSave(e:*):void {

			var parameterPool:ParameterPool=null;
			var code:String = null;

			if(view.dataSource) {
				var parameterPools:ArrayCollection= new ArrayCollection();
				for each (var data:Object in view.dataSource)
				{
					var parameterId:Object = data[DATA_FIELD_PARAMETER_ID];
					if ( parameterId && ArrayUtil.getItemIndex(parameterId,updateParameterIds)>-1) {					

						for (code in data)
						{
							if(DATA_FIELD_PREFIX==code.substr(0,2)) {
								parameterPool = new ParameterPool();
								parameterPool.parameterId=(parameterId as Number);

								parameterPool.parameterTypeId=(Number)(code.substr(2));
								parameterPool.value=data[code];

								parameterPools.addItem(parameterPool);
							}
						}					

					} else {
						parameterId=data[DATA_FIELD_DUMMY_PARAMETER_ID];
						if (parameterId) {

							for (code in data)
							{
								if(DATA_FIELD_PREFIX==code.substr(0,2)) {
									parameterPool = new ParameterPool();
									parameterPool.parameterId=-(parameterId as Number);

									parameterPool.parameterTypeId=(Number)(code.substr(2));
									parameterPool.value=data[code];

									parameterPools.addItem(parameterPool);
								}
							}	
						}
					}
				}
			}

			var parameterPoolListObject:ParameterPoolListObject =new ParameterPoolListObject();
			parameterPoolListObject.parameterPools=parameterPools;
			parameterPoolListObject.testcaseScriptId=_view.testcaseScriptId;
			parameterPoolListObject.removeParameterIds=this.removeParameterIds;

			var parameterPoolEvent:ParameterPoolEvent=new ParameterPoolEvent(ParameterPoolEvent.TYPE_save);			
			parameterPoolEvent.parameterPoolListObject=parameterPoolListObject;
			dispatchEvent(parameterPoolEvent);
		}


//		private function onClone(e:*):void {
//			if(view.dataSource) {
//				var selectedIndex:int =view.parameterPoolDataGrid.selectedIndex;
////				view.dataSource.addItem(new Object());
//			}
//		}

		private function onCreate(e:*):void {

			var object:Object = new Object();

			for each (var dataGridColumn:DataGridColumn in view.parameterPoolDataGrid.columns) {
				if(DATA_FIELD_PREFIX==dataGridColumn.dataField.substr(0,2)) {
					object[dataGridColumn.dataField]="";
				}
			}

			if(view.dataSource) {
//				var selectedIndex:int =view.parameterPoolDataGrid.selectedIndex;
//				if(selectedIndex>-1){
//					view.dataSource.addItemAt(new Object(),selectedIndex+1);	
//				} else {
//				}
			} else {
				view.dataSource = new ArrayCollection();

			}
			view.dataSource.addItem(object);
		}

		private function onLoad(e:*):void {
			var parameterPoolEvent:ParameterPoolEvent=new ParameterPoolEvent(ParameterPoolEvent.TYPE_findByTestcaseScriptId);			
			parameterPoolEvent.testcaseScriptId=_view.testcaseScriptId;
			dispatchEvent(parameterPoolEvent);
		}

		[ResponseHandler("{com.obas.event.ParameterPoolEvent.RETURN_ID}")]
		public function onParameterPoolEvent(event:CommandCompletionEvent):void
		{
			if (event.error)
			{
				ErrorManager.showErrorMessage(ResourceUtil.getErrorString("", event.error));
				return;
			}
			var request:ParameterPoolEvent=event.request as ParameterPoolEvent;
			switch (request.actionType)
			{

				case ParameterPoolEvent.TYPE_save:
					removeParameterIds=new Array();
					switchEditLabel(false);
					onLoad(event);
					break;
				case ParameterPoolEvent.TYPE_findByTestcaseScriptId:
					var parameterPoolGrid:ParameterPoolGrid=event.result as ParameterPoolGrid;
					var parameterTypes:ArrayCollection=parameterPoolGrid.parameterTypes;

//					var len:int = 1;
//
//					if(null!=parameterTypes) {
//						len=len+parameterTypes.length;
//					}
					var columns:Array=new Array();


					var dataGridColumn:DataGridColumn=new DataGridColumn();
					dataGridColumn.headerText="参数标识";
					//						dataGridColumn.dataField=parameterType.code;
					dataGridColumn.dataField=DATA_FIELD_PARAMETER_ID;					
					dataGridColumn.width=80;
					dataGridColumn.editable=false;
					dataGridColumn.setStyle("textAlign","center");
					columns.push(dataGridColumn);	

					if(null!=parameterTypes) {
						for (var i:int=0; i < parameterTypes.length; i++)
						{						
							var parameterType:ParameterType=parameterTypes.getItemAt(i) as ParameterType;
							//
							dataGridColumn=new DataGridColumn();
							dataGridColumn.headerText=parameterType.name;
							//						dataGridColumn.dataField=parameterType.code;
							dataGridColumn.dataField="PT"+parameterType.id;
							dataGridColumn.width=120;
//							dataGridColumn.setStyle("textAlign","center");
							dataGridColumn.headerRenderer=itemRendererFactory;
//							dataGridColumn.itemRenderer=itemRendererFactory;
							columns.push(dataGridColumn);
								//						
						}
					}
					_view.parameterPoolDataGrid.columns=columns;
					_view.dataSource=parameterPoolGrid.parameters;

					break;
			}
		}

	}
}

